#include "viewmodesettingsform.h"
#include "ui_viewmodesettingsform.h"

viewModeSettingsForm::viewModeSettingsForm(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::viewModeSettingsForm)
{
    m_ui->setupUi(this);

    readSettings();
    mySettings = new settingsDialog(this);

    QStringList headerTitles;
    headerTitles << "Name" << "Type" << "Default";
    m_ui->viewModeTree->setHeaderLabels (headerTitles);

    drawTreeView();
    setModes();
}

viewModeSettingsForm::~viewModeSettingsForm()
{
    delete m_ui;
    delete mySettings;
}

void viewModeSettingsForm::readSettings()
{
    QSettings settings("Folder index", "Settings");
    m_ui->statupCheck->setChecked( settings.value( "Run WS", false ).toBool() );
    m_ui->runHiddenCheck->setChecked( settings.value( "rhidden", false ).toBool() );
    m_ui->nativeIconsCheck->setChecked( settings.value( "nativeI", false ).toBool() );
    m_ui->autoExpandCheck->setChecked( settings.value( "autoexpand", false ).toBool() );
    m_ui->subfoldersCheck->setChecked( settings.value( "prsubfolders", false ).toBool() );
}

void viewModeSettingsForm::writeSettings()
{
    QSettings settings("Folder index", "Settings");
    settings.setValue( "Run WS", m_ui->statupCheck->isChecked() );
    settings.setValue( "rhidden", m_ui->runHiddenCheck->isChecked() );
    settings.setValue( "nativeI", m_ui->nativeIconsCheck->isChecked() );
    settings.setValue( "autoexpand", m_ui->autoExpandCheck->isChecked() );
    settings.setValue( "prsubfolders", m_ui->subfoldersCheck->isChecked() );

    if ( m_ui->statupCheck->isChecked() )
    {
        QSettings set( "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat );
        set.setValue( "folderIndex", QString("\"%1\"").arg(qApp->applicationFilePath()) );
    }
    else
    {
        QSettings set( "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat );
        set.remove( "folderIndex" );
    }
    setModes();
}

void viewModeSettingsForm::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

QString viewModeSettingsForm::getSettingsFolderPath()
{
    TCHAR szPath[MAX_PATH];
    QString path;

    SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szPath );

    for ( uint i = 0; i < 260; i++)
    {
            if ( szPath[i] != 0 )
                    path += (char)szPath[i];
            else
                    break;
    }

    path.replace( "\\", "/" );
    path.append( "/Folder index/settings" );
    return path;
}

void viewModeSettingsForm::drawTreeView()
{
    m_ui->viewModeTree->clear();

    QStringList nameList;
    QDir dir( getSettingsFolderPath() );
    QStringList myList = dir.entryList( QStringList("*.lvm"),
                                        QDir::NoDotAndDotDot|QDir::Files|QDir::NoSymLinks);
    if ( myList.count() > 0 )
    {
        for ( int i = 0; i < myList.count(); i++ )
        {
            QTreeWidgetItem * item = new QTreeWidgetItem( m_ui->viewModeTree );
            item->setText( 0, myList.at(i).left( myList.at(i).lastIndexOf('.') ) );
            item->setText( 1, "User" );
        }
        setDefault( 0 );
    }
}

void viewModeSettingsForm::currentModeChanged( const QString& modeName )
{
    if ( !modeName.isEmpty() )
    {
        QList<QTreeWidgetItem*> items = m_ui->viewModeTree->findItems( modeName, Qt::MatchFixedString, 0 );
        if ( items.size() > 0 )
        {
            m_ui->viewModeTree->clearSelection();
            m_ui->viewModeTree->setCurrentItem( items.at(0) );
            mySettings->getSettings( m_ui->viewModeTree->currentItem()->text(0) );
        }
    }
}

QString viewModeSettingsForm::getDefaultViewMode()
{
    QString ret;
    QList<QTreeWidgetItem*> items = m_ui->viewModeTree->findItems( "Yes", Qt::MatchFixedString, 2 );
    if ( items.size() > 0 )
        return items.at(0)->text(0);
    return QString::null;
}

QString viewModeSettingsForm::getCurrentViewMode()
{
    if ( m_ui->viewModeTree->currentItem() )
        return m_ui->viewModeTree->currentItem()->text(0);
    return "";
}

QStringList viewModeSettingsForm::getViewModes()
{
    QStringList retList;
    QTreeWidgetItemIterator it(m_ui->viewModeTree);
    while (*it)
    {
        retList.append( (*it)->text(0) );
        ++it;
    }
    return retList;
}

bool viewModeSettingsForm::run_form()
{
    // move to center
    QRect frect = frameGeometry();
    frect.moveCenter(QDesktopWidget().availableGeometry().center());
    move(frect.topLeft());

    return exec();
}

void viewModeSettingsForm::on_addButton_clicked()
{
    if ( mySettings->run_form( 0 ) )
        drawTreeView();
}

void viewModeSettingsForm::on_modifyButton_clicked()
{
    if ( m_ui->viewModeTree->currentItem() &&
         m_ui->viewModeTree->currentItem()->text(1).toLower() == "user" )
    {
        if ( mySettings->run_form( 1, m_ui->viewModeTree->currentItem()->text(0) ) )
            drawTreeView();
    }
}

void viewModeSettingsForm::on_cloneButton_clicked()
{
    if ( m_ui->viewModeTree->currentItem() )
    {
        if ( mySettings->run_form( 2, m_ui->viewModeTree->currentItem()->text(0) ) )
            drawTreeView();
    }
}

void viewModeSettingsForm::on_removeButton_clicked()
{
    if ( !m_ui->viewModeTree->currentItem() ||
         m_ui->viewModeTree->currentItem()->text(1).toLower() == "system" )
        return;

    switch( QMessageBox::warning( this, "Delete view mode",
                                  "Do you really want to delete this view mode?",
                                  "Yes",
                                  "No", 0, 0, 1 ) )
    {
        case 1:
        {
            return;
        }
    }

    if ( QFile::remove( getSettingsFolderPath() + QString("/%1.lvm").arg( m_ui->viewModeTree->currentItem()->text(0) ) ) )
    {
        m_ui->viewModeTree->takeTopLevelItem(
                m_ui->viewModeTree->indexOfTopLevelItem(
                        m_ui->viewModeTree->currentItem() ) );
        setDefault( 0 );
    }
    else
        QMessageBox::critical( this, "Error", "Couldn't delete file!" );
}

void viewModeSettingsForm::on_actionExport_triggered()
{
    if ( !m_ui->viewModeTree->currentItem() )
        return;

    QString path = QFileDialog::getSaveFileName ( this, tr("Export mode"),
                                   "", tr("Modes (*.ini)") );

    mySettings->exportCustomMode( m_ui->viewModeTree->currentItem()->text(0), path );
}

void viewModeSettingsForm::on_actionImport_triggered()
{
    QString path = QFileDialog::getOpenFileName ( this, tr("Import mode"),
                                   "", tr("Modes (*.ini)") );
    QString name;
    if ( mySettings->importCustomMode( path, name ) )
    {
        QStringList nameList;
        nameList << name << "User";
        m_ui->viewModeTree->insertTopLevelItem( 0, new QTreeWidgetItem( nameList, 0 ) );
    }
}

void viewModeSettingsForm::on_defaultButton_clicked()
{
    if ( m_ui->viewModeTree->currentItem() )
        setDefault( m_ui->viewModeTree->currentItem()->text(0) );
}

void viewModeSettingsForm::setDefault( const QString &name )
{
    QString defMode = name;
    bool anyDef = false;
    if ( defMode.isEmpty() )
    {
        QSettings settings("Folder index", "Settings");
        defMode = settings.value("Default mode", "DOS" ).toString();
    }

    m_ui->viewModeTree->setUpdatesEnabled(false);
    for ( int i = 0; i < m_ui->viewModeTree->topLevelItemCount(); i++ )
    {
        m_ui->viewModeTree->topLevelItem(i)->setText( 2, "" );
        if ( m_ui->viewModeTree->topLevelItem(i)->text(0) == defMode )
        {
            m_ui->viewModeTree->topLevelItem(i)->setText( 2, "Yes" );
            anyDef = true;
            break;
        }
    }
    m_ui->viewModeTree->setUpdatesEnabled(true);

    QSettings settings("Folder index", "Settings");
    settings.setValue("Default mode", defMode );

    if ( !anyDef )
    {
        m_ui->viewModeTree->topLevelItem(0)->setText( 2, "Yes" );
        QSettings settings("Folder index", "Settings");
        settings.setValue("Default mode", m_ui->viewModeTree->topLevelItem(0)->text(0) );
    }
}

void viewModeSettingsForm::on_saveButton_clicked()
{
    writeSettings();
    accept();
}

void viewModeSettingsForm::on_closeButton_clicked()
{
    setModes();
    reject();
}

void viewModeSettingsForm::on_subfoldersCheck_stateChanged(int state)
{
    if ( state == 0 )
        m_ui->autoExpandCheck->setChecked( false );
}

void viewModeSettingsForm::setModes()
{
    QSettings settings("Folder index", "Settings");
    settings.setValue("Modes", getViewModes().join(";") );
}

void viewModeSettingsForm::on_viewModeTree_itemDoubleClicked(QTreeWidgetItem* item, int)
{
    if ( item )
        on_modifyButton_clicked();
}
